package org.ajaxgroovyshell;

import groovy.lang.Binding;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.codehaus.groovy.tools.shell.Groovysh;
import org.codehaus.groovy.tools.shell.IO;

public class ConsoleRunner extends Thread {

	public final PipedInputStream pis = new PipedInputStream();
	public final PipedOutputStream pos = new PipedOutputStream();

	Map<String, Object> mBindings = new HashMap<String, Object>();
	
	public ConsoleRunner() {
	}
	
	@Override
	public void run() {
		try {
			InputStream in = new PipedInputStream(pos);
			OutputStream out = new PipedOutputStream(pis);
			Binding binding = new Binding();
			for(String key: mBindings.keySet()) {
				binding.setVariable(key, mBindings.get(key));
			}

			final Groovysh groovy = new Groovysh(binding, new IO(in, out, out));
			groovy.run();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}
